package com.opages.netty.demo.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author daizhong.liu
 * @create 2021-12-03 11:08
 **/
public class GroupServer {
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;
    public GroupServer(String address,int port) {
        try {
            //创建服务端
            serverSocketChannel = ServerSocketChannel.open();
            //绑定地址
            serverSocketChannel.bind(new InetSocketAddress(address, port));
            //选择非阻塞
            serverSocketChannel.configureBlocking(false);
            //打开一个选择器
            selector = Selector.open();
            //注册accept事件到selector
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void listen() {
        try {
            while (true) {
                int select = selector.select(3000);
                if (select > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
                    while (keyIterator.hasNext()) {
                        SelectionKey selectionKey = keyIterator.next();
                        if (selectionKey.isAcceptable()) {
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.err.println(socketChannel.getRemoteAddress() + " 上线了.");
                        }
                        if (selectionKey.isReadable()) {
                            readContent(selectionKey);
                        }
                        keyIterator.remove();
                    }
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readContent(SelectionKey selectionKey)  {
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        try {
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = socketChannel.read(byteBuffer);
            if(read > 0) {
                forwardClient(new String(byteBuffer.array()),socketChannel);
            }
        }catch (IOException e) {
            e.printStackTrace();
            try {
                System.err.println(socketChannel.getRemoteAddress()+"下线了");
                selectionKey.cancel();
                socketChannel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }

    private void forwardClient(String content,SocketChannel self) {
        Set<SelectionKey> keys = selector.keys();
        Iterator<SelectionKey> keyIterator = keys.iterator();
        while (keyIterator.hasNext()) {
            SelectionKey selectionKey = keyIterator.next();
            SelectableChannel channel = selectionKey.channel();
            if(channel instanceof SocketChannel && channel != self) {
                SocketChannel otherChannel = (SocketChannel) channel;
                try {
                    otherChannel.write(ByteBuffer.wrap(content.getBytes()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        GroupServer groupServer = new GroupServer("127.0.0.1",8889);
        groupServer.listen();
    }

}
